package com.huangsm.book.designmodel.concurrentdatastructure;

import java.util.Queue;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 处理队列线程
 *
 * @author huang
 * @date 2019/2/20
 */
public class HandleQueueThread implements Runnable {
    private Queue q;
    private String name;
    Random random = new Random();

    public HandleQueueThread() {
    }

    public HandleQueueThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        try {
            for (int i = 0; i < 500; i++) {

                handleQueue(random.nextInt(1000));
                Thread.sleep(random.nextInt(100));
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public Object handleQueue(int index) {
        q.add(index);
        q.poll();
        return null;
    }

    public void initConcurrentLinkedQueue() {
        q = new ConcurrentLinkedQueue();
        for (int i = 0; i < 300; i++) {
            q.add(i);
        }
    }

    public void initLinkedBlockingQueue() {
        q = new LinkedBlockingQueue();
        for (int i = 0; i < 300; i++) {
            q.add(i
            );
        }
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        HandleQueueThread handleQueueThread=new HandleQueueThread();
        //handleQueueThread.initConcurrentLinkedQueue();
        handleQueueThread.initLinkedBlockingQueue();
        System.out.println(System.currentTimeMillis()-start);
    }
}
